package com.baidu.customview.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;

import com.baidu.customview.R;

/**
 * Created by Kvin on 2016/1/4.
 */
public class ScaleView extends View {
    private Paint paint;
    private int img;
    private Bitmap bitmap;

    public ScaleView(Context context) {
        super(context);
    }

    public ScaleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ScaleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ScaleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, paint);
    }

    private void init(Context context, AttributeSet attrs) {
        paint = new Paint();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScaleView);
        img = typedArray.getResourceId(R.styleable.ScaleView_img, R.mipmap.ic_launcher);
        typedArray.recycle();
        bitmap = getBitmap(img, 4);
    }

    //pic compress
    private Bitmap getBitmap(int img,int scale) {
        //在图片尺寸小于标准时，就用原图
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), img, options);
        options.inJustDecodeBounds = false;
//        while (options.outWidth / m > maxWidth ||options.outHeight/ m > maxHeight) {
//            m *= 2;
//        }
        options.inSampleSize = scale;
        return BitmapFactory.decodeResource(getResources(), img, options);
    }

    //pic magnify
    private Bitmap bigBitmap(int imgId, int scale) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imgId);
        Matrix mat = new Matrix();
        int sW = bitmap.getWidth();
        int sH = bitmap.getHeight();
        mat.setScale(sW * scale, sH * scale);
        return Bitmap.createBitmap(bitmap, 0, 0, sW, sH, mat, true);
    }

    //设置左边图的Top
    private float getPicTop(Bitmap bitmap) {
        return (getHeight() - bitmap.getHeight()) / 2;
    }

    //设置txt坐标Y
    private float getTxtY(String str) {
        Rect rect = new Rect();
        paint.getTextBounds(str, 0, 1, rect);
        return (this.getHeight() + rect.height()) / 2;
    }

}
